/*
Copyright (c) 2007,2007 Elizeu Nogueira da R. Jr.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.
    * Neither the name of the Elizeu Nogueira da R. Jr. nor the names of its 
      contributors may be used to endorse or promote products derived from this 
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package br.com.dreamsource.mobile.jmesql.io;

import javax.microedition.rms.*;
import javax.microedition.io.*;
import java.io.*;

public class RandomAccessFile implements DataInput, DataOutput {
    private static final int MAGIC = 0x52410001;
    private static final int RESERVED = 8;
    private static final int RECORD_SIZE = 256;
    
    private RecordStore recordStore;
    private byte[] recordData;
    private boolean recordModified;
    private int currentRecord;
    private int magic;
    private int fileSize;
    private int fileOffset;
    private int recordSize;
    
    private void ReadRecord(int recordNumber) throws IOException {
        try {
            recordData = recordStore.getRecord(recordNumber);
        } catch (InvalidRecordIDException e) {
            recordData = new byte[recordSize];
        } catch (RecordStoreException e) {
            throw new IOException(e.getClass().getName());
        }
    }
    
    private void WriteRecord(int recordNumber) throws IOException {
        try {
            recordStore.setRecord(recordNumber, recordData, 0, recordSize);
        } catch (InvalidRecordIDException e) {
            try {
                int recnum;
                
                do
                {
                    recnum = recordStore.addRecord(recordData, 0, recordSize);
                } while (recnum != recordNumber);
            } catch (RecordStoreException e2) {
                throw new IOException(e2.getClass().getName());
            }
        } catch (RecordStoreException e) {
            throw new IOException(e.getClass().getName());
        }
    }
    
    public RandomAccessFile(String filename, String mode) throws IOException {
        recordSize = RECORD_SIZE;
        
        if (mode.equals("r") || mode.equals("rw")) {
            try {
                recordStore = RecordStore.openRecordStore(filename, false);
                recordData = null;
                currentRecord = 0;
                recordModified = false;
                fileOffset = 0;
                fileSize = RESERVED; // Must be at least size of RESERVED Area
                magic = readInt();
                if (magic == MAGIC) {
                    fileSize = readInt();
                    fileOffset = RESERVED;
                } else {
                    fileSize = recordData.length;
                    recordSize = fileSize;
                    fileOffset = 0;
                }
            } catch (RecordStoreNotFoundException e) {
                
                if (mode.equals("rw")) {
                    try {
                        recordStore = RecordStore.openRecordStore(filename, true);
                        recordData = null;
                        currentRecord = 0;
                        recordModified = false;
                        fileSize = RESERVED;
                        fileOffset = RESERVED;
                        magic = MAGIC;
                    } catch (Exception e2) {
                        throw new IOException(e.getClass().getName());
                    }
                } else {
                    throw new IOException("File not found");
                }
            } catch (RecordStoreException e) {
                throw new IOException(e.getClass().getName());
            }
        } else {
            throw new IllegalArgumentException();
        }
    }
    
    public void close() throws IOException {
        try {
            if (magic == MAGIC) {
                fileOffset = 0;
                writeInt(MAGIC);
                writeInt(fileSize);
                WriteRecord(currentRecord);
            }
        } finally {
            try {
                recordStore.closeRecordStore();
            } catch (RecordStoreException e) {
            }
        }
    }
    
    public byte readByte() throws IOException {
        byte byteValue;
        
        if (fileOffset >= 0) {
            if (fileOffset < fileSize) {
                int recordNumber = fileOffset / recordSize + 1;
                int recordOffset = fileOffset % recordSize;
                
                if (recordNumber != currentRecord) {
                    if (recordModified)
                        WriteRecord(currentRecord);
                    
                    ReadRecord(recordNumber);
                    currentRecord = recordNumber;
                    recordModified = false;
                }
                
                byteValue = recordData[recordOffset];
                fileOffset++;
            } else {
                throw new EOFException();
            }
        } else {
            throw new IOException("Invalid offset");
        }
        
        return byteValue;
    }
    
    public void writeByte(int byteValue) throws IOException {
        if (fileOffset >= 0) {
            int recordNumber = fileOffset / recordSize + 1;
            int recordOffset = fileOffset % recordSize;
            
            if (recordNumber != currentRecord) {
                if (recordModified)
                    WriteRecord(currentRecord);
                
                ReadRecord(recordNumber);
                currentRecord = recordNumber;
                recordModified = false;
            }
            
            recordData[recordOffset] = (byte)byteValue;
            recordModified = true;
            fileOffset++;
            
            if (fileOffset >= fileSize)
                fileSize = fileOffset;
        } else {
            throw new IOException("Invalid offset");
        }
    }
    
    public boolean readBoolean() throws IOException {
        return (readByte() != 0);
    }
    
    public char readChar() throws IOException {
        byte a = readByte();
        byte b = readByte();
        
        char ch = (char)(((a & 0xff) << 8) | (b & 0xff));
        
        return ch;
    }
    
    public void readFully(byte[] b) throws IOException {
        for (int i=0;i<b.length;i++)
            b[i] = readByte();
    }
    
    public void readFully(byte[] b, int off, int len) throws IOException {
        for (int i=0;i<len;i++)
            b[off+i] = readByte();
    }
    
    public int readInt() throws IOException {
        byte a = readByte();
        byte b = readByte();
        byte c = readByte();
        byte d = readByte();
        
        int intVal = ((a & 0xff) << 24) |
                ((b & 0xff) << 16) |
                ((c & 0xff) << 8) |
                (d & 0xff);
        
        return intVal;
    }
    
    public long readLong() throws IOException {
        int a = readInt();
        int b = readInt();
        
        long longVal = a << 32 | b;
        
        return longVal;
    }
    
    public short readShort() throws IOException {
        byte a = readByte();
        byte b = readByte();
        
        int intVal = ((a & 0xff) << 8) |
                (b & 0xff);
        
        return (short)intVal;
    }
    
    public int readUnsignedByte() throws IOException {
        return readByte() & 0xff;
    }

    public int readUnsignedShort() throws IOException {
        byte a = readByte();
        byte b = readByte();
        
        int uShortVal = ((a & 0xff) << 8) |
                (b & 0xff);
        
        return uShortVal;
    }
    
    public String readUTF() throws IOException {
        String s = null;
        int tmp = fileOffset;
        int len = readUnsignedShort();
        
        fileOffset = tmp;
        byte[] byteArray = new byte[len+2];
        readFully(byteArray);
        
        ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray);
        DataInputStream in = new DataInputStream(inputStream);
        s = in.readUTF();
        
        return s;
    }
    
    public int skipBytes(int n) throws IOException {
        if (n > 0) {
            fileOffset += n;
            if (fileOffset > fileSize)
                throw new EOFException();
        } else {
            throw new IOException("Invalid argument");
        }
        
        return n;
    }
    
    public void write(byte[] b) throws IOException {
        for (int i=0;i<b.length;i++)
            writeByte(b[i]);
    }
    
    public void write(byte[] b, int off, int len) throws IOException {
        for (int i=0;i<len;i++)
            writeByte(b[off+i]);
    }
    
    public void write(int b) throws IOException {
        writeByte((byte)b);
    }
    
    public void writeBoolean(boolean v) throws IOException {
        if (v)
            writeByte((byte)1);
        else
            writeByte((byte)0);
    }
    
    public void writeChar(int v) throws IOException {
        writeByte((v >> 8) & 0xff);
        writeByte(v & 0xff);
    }
    
    public void writeChars(String s) throws IOException {
        for (int i=0;i<s.length();i++)
            writeChar(s.charAt(i));
    }
    
    public void writeInt(int v) throws IOException {
        writeByte((v >> 24) & 0xff);
        writeByte((v >> 16) & 0xff);
        writeByte((v >> 8) & 0xff);
        writeByte(v & 0xff);
    }
    
    public void writeLong(long v) throws IOException {
        writeInt((int)(v >> 32));
        writeInt((int)(v & 0xffffffff));
    }
    
    public void writeShort(int v) throws IOException {
        writeByte((v >> 8) & 0xff);
        writeByte(v & 0xff);
    }
    
    public void writeUTF(String s) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(outputStream);
        out.writeUTF(s);
        
        byte[] byteArray = outputStream.toByteArray();
        for (int i=0;i<byteArray.length;i++)
            writeByte(byteArray[i]);
    }
    
    public int getFilePointer() {
        return fileOffset - RESERVED;
    }
    
    public void seek(int offset) {
        if (offset >= 0) {
            fileOffset = offset + RESERVED;
            if (fileOffset > fileSize)
                fileOffset = fileSize;
        } else {
            fileOffset = fileSize;
        }
    }
    
    public double readDouble() throws IOException {
        return Double.longBitsToDouble(readLong());
    }
    
    public void writeDouble(double param) throws IOException {
        writeLong(Double.doubleToLongBits(param));
    }
    
    public void writeFloat(float param) throws IOException {
        writeInt(Float.floatToIntBits(param));
    }
    
    public float readFloat() throws IOException {
        return Float.intBitsToFloat(readInt());
    }
    
}
